package com.cy.lib.net.webservice;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 *
 */
public class WebXMLParser {

    static XmlPullParserFactory mXmlPullParserFactory;
    static XmlPullParser mXmlPullParser;


    private synchronized XmlPullParserFactory getXmlPullParserFactory() throws XmlPullParserException {
        if (mXmlPullParserFactory == null) {
            mXmlPullParserFactory = XmlPullParserFactory.newInstance();
        }
        return mXmlPullParserFactory;
    }

    private synchronized XmlPullParser getXmlPullParser() throws XmlPullParserException {
        if (mXmlPullParser == null) {
            mXmlPullParser = getXmlPullParserFactory().newPullParser();
        }
        return mXmlPullParser;
    }

    public synchronized String parseXml(String text) {

        // <?xml version="1.0" encoding="utf-8"?>
        // <string
        // xmlns="http://tempuri.org/">NXSJlUOgAe/+TRo8aGezVupwCCJG6Kg/3kxdijK5u1C96lLj/eeVJA==</string>

        try {
            XmlPullParser parser = getXmlPullParser();
            ByteArrayInputStream bais = new ByteArrayInputStream(text.getBytes());
            parser.setInput(bais, "utf-8");
            boolean done = false;
            while (!done) {
                int eventType = parser.next();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        String nextText = parser.nextText();
                        bais.close();
                        done = true;
                        return nextText;
                    case XmlPullParser.END_DOCUMENT:
                        return text;
                }
            }
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return text;
    }
}
